package com.menghao.rpc.serialize.hessian;

import com.caucho.hessian.io.Hessian2Output;
import com.menghao.rpc.serialize.ObjectOutput;

import java.io.IOException;
import java.io.OutputStream;

/**
 * <p>Hessian序列化.<br>
 *
 * @author MarvelCode.
 */
public class HessianObjectOutput implements ObjectOutput {

    private Hessian2Output hessian2Output;

    public HessianObjectOutput(OutputStream os) {
        hessian2Output = new Hessian2Output(os);
        hessian2Output.setSerializerFactory(HessianSerializer.SERIALIZER_FACTORY);
    }

    @Override
    public void writeObject(Object obj) throws IOException {
        hessian2Output.writeObject(obj);
    }

    @Override
    public void write(int b) throws IOException {
        hessian2Output.writeInt(b);
    }

    @Override
    public void write(byte[] b) throws IOException {
        hessian2Output.writeBytes(b);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        hessian2Output.writeBytes(b, off, len);
    }

    @Override
    public void writeBoolean(boolean v) throws IOException {
        hessian2Output.writeBoolean(v);
    }

    @Override
    public void writeByte(int v) throws IOException {
        hessian2Output.writeBytes(new byte[]{(byte) v});
    }

    @Override
    public void writeShort(int v) throws IOException {
        hessian2Output.writeInt(v);
    }

    @Override
    public void writeChar(int v) throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void writeInt(int v) throws IOException {
        hessian2Output.writeInt(v);
    }

    @Override
    public void writeLong(long v) throws IOException {
        hessian2Output.writeLong(v);
    }

    @Override
    public void writeFloat(float v) throws IOException {
        hessian2Output.writeDouble(v);
    }

    @Override
    public void writeDouble(double v) throws IOException {
        hessian2Output.writeDouble(v);
    }

    @Override
    public void writeBytes(String s) throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void writeChars(String s) throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void writeUTF(String s) throws IOException {
        hessian2Output.writeString(s);
    }

    @Override
    public void flush() throws IOException {
        hessian2Output.flush();
    }

    @Override
    public void close() throws IOException {
        hessian2Output.close();
    }
}
